Skip to content

Latest commit

 

History

History

1138-Alphabet Board Path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

1138. Alphabet Board Path

On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

We may make the following moves:

  • 'U' moves our position up one row, if the position exists on the board;
  • 'D' moves our position down one row, if the position exists on the board;
  • 'L' moves our position left one column, if the position exists on the board;
  • 'R' moves our position right one column, if the position exists on the board;
  • '!' adds the character board[r][c] at our current position (r, c) to the answer.

(Here, the only positions that exist on the board are positions with letters on them.)

Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.

Example 1:

Input: target = "leet" Output: "DDR!UURRR!!DDD!" 

Example 2:

Input: target = "code" Output: "RR!DDRR!UUL!R!" 

Constraints:

  • 1 <= target.length <= 100
  • target consists only of English lowercase letters.

Solutions (Ruby)

1. Solution

# @param {String} target# @return {String}defalphabet_board_path(target)s=[0,0]ret=''target.each_bytedo |c| t=[(c - 97) / 5,(c - 97) % 5]ret += path_to(s,t) + '!'s=tendretend# @param {Integer[]} start# @param {Integer[]} target# @return {String}defpath_to(start,target)ifstart == target''elsifstart == [5,0]'U' + path_to([4,0],target)elsiftarget == [5,0]path_to(start,[4,0]) + 'D'elsev_dir=start[0] > target[0] ? 'U' : 'D'h_dir=start[1] > target[1] ? 'L' : 'R'v_dir * (start[0] - target[0]).abs + h_dir * (start[1] - target[1]).absendend

Solutions (Rust)

1. Solution

implSolution{pubfnalphabet_board_path(target:String) -> String{letmut s = (0,0);letmut ret = String::new();for c in target.bytes(){let t = ((c - b'a') / 5,(c - b'a') % 5); ret = ret + &Self::path_to(s, t) + "!"; s = t;} ret }fnpath_to(start:(u8,u8),target:(u8,u8)) -> String{if start == target {String::new()}elseif start == (5,0){"U".to_string() + &Self::path_to((4,0), target)}elseif target == (5,0){Self::path_to(start,(4,0)) + "D"}else{letmut moves = String::new();if start.0 > target.0{ moves += &"U".repeat((start.0 - target.0)asusize)}else{ moves += &"D".repeat((target.0 - start.0)asusize)}if start.1 > target.1{ moves += &"L".repeat((start.1 - target.1)asusize);}else{ moves += &"R".repeat((target.1 - start.1)asusize);} moves }}}
close